﻿using System;
using System.Web.ModelBinding;

namespace Morus.Presentation
{
    public class PageView<TModel> : PageView, IView<TModel>
        where TModel : class, new()
    {
        private TModel _model;
        private bool _modelBound;
        private IValueProvider _valueProvider;

        public TModel Model
        {
            get
            {
                if (_model == null)
                {
                    throw new InvalidOperationException("The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings.");
                }

                if (!_modelBound)
                {
                    if (TryUpdateModel(_model, ValueProvider))
                    {
                        _modelBound = true;
                        return _model;
                    }
                    _modelBound = true;
                }
                return _model;
            }
            set
            {
                _model = value;
            }
        }

        public IValueProvider ValueProvider
        {
            get
            {
                return _valueProvider ?? (_valueProvider = ValueProviderFactories.Factories.GetValueProvider(new ModelBindingExecutionContext(HttpContext, ModelState)));
            }
            set
            {
                _valueProvider = value;
            }
        }

        public bool TryUpdateModel(TModel model)
        {
            return TryUpdateModel(model);
        }

        public bool TryUpdateModel(TModel model, IValueProvider valueProvider)
        {
            return TryUpdateModel(model, valueProvider);
        }

        public void UpdateModel(TModel model)
        {
            UpdateModel(model);
        }

        public void UpdateModel(TModel model, IValueProvider valueProvider)
        {
            UpdateModel(model, valueProvider);
        }
    }
}